<template>
	<div>
		<div class="control-content app-control-multieditviewpanel__content">
			<template v-if="panelStyle == 'TAB_TOP'">
				<a-tabs
					v-model:activeKey="activeTab"
					class="app-control-multieditviewpanel__content__tab"
					type="editable-card"
					@edit="handleEdit"
					:hideAdd="!showButton"
				>
					<a-tab-pane
						class="app-control-multieditviewpanel__content__tab"
						v-for="item in items"
						:key="item.id"
						:tab="item.label"
						:forceRender="true"
					>
						<slot
							:itemId="item.id"
							:context="item.context"
							:viewParams="item.viewParams"
						>
						</slot>
					</a-tab-pane>
				</a-tabs>
			</template>
			<template v-else>
				<div
					class="app-control-multieditviewpanel__content__item"
					v-for="item in items"
					:key="item.id"
				>
					<CloseOutlined @click="handleEdit(item.id, 'remove')" />
					<slot
						:itemId="item.id"
						:context="item.context"
						:viewParams="item.viewParams"
					>
					</slot>
				</div>
			</template>
		</div>
		<div
			v-if="showButton && panelStyle == 'ROW'"
			class="control-footer app-control-multieditviewpanel__footer"
		>
			<AppButton
				type="primary"
				@click="($event: MouseEvent | string) => handleEdit($event, 'add')"
			>
				<PlusOutlined />
				{{ $t('widget.multieditviewpanel.add') }}
			</AppButton>
		</div>
	</div>
</template>
<script setup lang="ts">
import { IParam } from '@/core';
import { CloseOutlined, PlusOutlined } from '@ant-design/icons-vue';
import { multiEditViewPanelProps } from './multi-editview-panel';
const props = defineProps(multiEditViewPanelProps);
const showButton = ref(true);
const activeTab = ref<string>('');
const emit = defineEmits<{
	(name: 'add', event: MouseEvent): void;
	(name: 'remove', item: IParam): void;
}>();
//	当前行为
let curAction: 'ADD' | 'REMOVE' | null = null;

watch(
	() => props.items,
	(newVal: IParam[]) => {
		if (newVal && newVal.length > 0) {
			if (!activeTab.value) {
				activeTab.value = newVal[0].id;
			}
			//	增加时跳转至新增项
			if (curAction === 'ADD') {
				activeTab.value = newVal[newVal.length - 1].id;
			}
		}
		curAction = null;
	},
	{ immediate: true, deep: true }
);

const handleEdit = (key: any, action: string) => {
	if (action == 'add') {
		curAction = 'ADD';
		emit('add', key as MouseEvent);
	}
	if (action == 'remove') {
		curAction = 'REMOVE';
		const item = props.items.find((item: IParam) => item.id === key);
		if (item) {
			if (item.id === activeTab.value) {
				activeTab.value = '';
			}
			emit('remove', item);
		}
	}
};
</script>
